package com.yungu.swift.system.marketing.thread;

import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.system.marketing.dao.MarketingGiftCodeMapper;
import com.yungu.swift.system.marketing.model.dto.MarketingGiftCodeDto;
import com.yungu.swift.system.marketing.model.param.AdminCouponGiftParam;
import com.yungu.swift.utils.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Description:
 * @Author cuixiuyin
 * @Date 2018/11/28 15:18
 * @Version 1.0
 */
public class MarketingGiftCodeThread implements Runnable {

    /**
     * 兑换码/口令码是否使用 1 已使用 0 未使用
     */
    public final static int VERIFY_MARKETING_GIFT_USED = 1;
    public final static int VERIFY_MARKETING_GIFT_UNUSED = 0;

    // 1. 自动生成 2. 导入码库
    public static final int GIFT_CREATE_TYPE_AUTO = 1;
    public static final int GIFT_CREATE_TYPE_IMPORT = 2;

    // 1. 兑换码 2.口令
    public static final int GIFT_CODE_TYPE_REDEMM_CODE = 1;
    public static final int GIFT_CODE_TYPE_PASSWORDS_CODE = 2;

    private AdminCouponGiftParam couponGiftParam;
    private String giftUuid;
    private MarketingGiftCodeMapper marketingGiftCodeMapper;

    public MarketingGiftCodeThread(AdminCouponGiftParam couponGiftParam, String giftUuid, MarketingGiftCodeMapper
            marketingGiftCodeMapper) {
        this.couponGiftParam = couponGiftParam;
        this.giftUuid = giftUuid;
        this.marketingGiftCodeMapper = marketingGiftCodeMapper;
    }

    @Override
    public void run() {
        // 兑换码
        if (GIFT_CODE_TYPE_REDEMM_CODE == couponGiftParam.getCodeType()) {
            handleRedemmCode();
        }
        // 口令
        if (GIFT_CODE_TYPE_PASSWORDS_CODE == couponGiftParam.getCodeType()) {
            handlePasswordsCode();
        }
    }

    private void handleRedemmCode() {
        List<MarketingGiftCodeDto> marketingGiftCodeDtoList = new ArrayList<>();
        List<String> redeemCodes = new ArrayList<>();
        Integer createCodeType = couponGiftParam.getCreateCodeType();
        // 自动生成
        if (createCodeType != null && createCodeType == GIFT_CREATE_TYPE_AUTO) {
            redeemCodes = autoCreateRedeemCodes(couponGiftParam.getRemainNumber());
        }
        // 手动导入
        if (createCodeType != null && createCodeType == GIFT_CREATE_TYPE_IMPORT) {
            redeemCodes = couponGiftParam.getRedeemCodes();
        }
        // 过滤数据库中重复的兑换码
        redeemCodes = filterRepeatRedeemCodes(redeemCodes);

        for (String redeemCode : redeemCodes) {
            MarketingGiftCodeDto marketingGiftCodeDto = new MarketingGiftCodeDto();
            marketingGiftCodeDto.setUuid(StringUtils.buildUUID());
            marketingGiftCodeDto.setGiftUuid(giftUuid);
            marketingGiftCodeDto.setCode(redeemCode);
            marketingGiftCodeDto.setAppid(couponGiftParam.getAppid());
            marketingGiftCodeDto.setAgentUuid(couponGiftParam.getAgentUuid());
            marketingGiftCodeDto.setCompanyUuid(couponGiftParam.getCompanyUuid());
            marketingGiftCodeDto.setCreateBy(couponGiftParam.getUserUuid());
            marketingGiftCodeDto.setCreateOn(new Date());
            marketingGiftCodeDto.setUsed(VERIFY_MARKETING_GIFT_UNUSED);
            marketingGiftCodeDto.setCodeType(GIFT_CODE_TYPE_REDEMM_CODE);
            marketingGiftCodeDtoList.add(marketingGiftCodeDto);
        }
        // 添加兑换码
        if (!marketingGiftCodeDtoList.isEmpty()) {
            marketingGiftCodeMapper.addBatch(marketingGiftCodeDtoList);
        }
    }

    private void handlePasswordsCode() {
        MarketingGiftCodeDto giftCodeDto = new MarketingGiftCodeDto();
        giftCodeDto.setUuid(StringUtils.buildUUID());
        giftCodeDto.setGiftUuid(giftUuid);
        giftCodeDto.setCode(couponGiftParam.getPasswordsCode());
        giftCodeDto.setAppid(couponGiftParam.getAppid());
        giftCodeDto.setAgentUuid(couponGiftParam.getAgentUuid());
        giftCodeDto.setCompanyUuid(couponGiftParam.getCompanyUuid());
        giftCodeDto.setCreateBy(couponGiftParam.getUserUuid());
        giftCodeDto.setCreateOn(new Date());
        giftCodeDto.setUsed(VERIFY_MARKETING_GIFT_UNUSED);
        giftCodeDto.setCodeType(GIFT_CODE_TYPE_PASSWORDS_CODE);
        marketingGiftCodeMapper.add(giftCodeDto);
    }

    /**
     * 过滤数据库中的重复兑换码
     *
     * @return
     */
    private List<String> filterRepeatRedeemCodes(List<String> redeemCodeList) {
        // 获取数据库中重复的兑换码
        if (!redeemCodeList.isEmpty()) {
            List<String> repeatRedeemCodes = marketingGiftCodeMapper.findRepeatRedeemCodes(redeemCodeList);
            if (repeatRedeemCodes.isEmpty()) {
                return redeemCodeList;
            }
            // 保存旧大小
            int oldSize = redeemCodeList.size();
            // 排除重复
            redeemCodeList.removeAll(repeatRedeemCodes);
            // 保存新大小
            int newSize = redeemCodeList.size();
            // 补全兑换码
            redeemCodeList.addAll(autoCreateRedeemCodes(oldSize - newSize));
            return filterRepeatRedeemCodes(redeemCodeList);
        }
        return redeemCodeList;
    }

    /**
     * 生成指定数量不重复的 2位英文 4位数字拼接的 随机位置的兑换码
     *
     * @param createCount
     * @return
     */
    private List<String> autoCreateRedeemCodes(int createCount) {
        List<String> redeemCodeList = new ArrayList<>();
        while (redeemCodeList.size() != createCount) {
            createNoRepeatRedeemCode(redeemCodeList);
        }
        return redeemCodeList;
    }

    /**
     * 用于递归生成不重复的兑换码 兑换码为6位的大小写字母数字随机排列
     *
     * @param redeemCodeList
     * @return
     */
    private void createNoRepeatRedeemCode(List<String> redeemCodeList) {
        String redeemCode = createRandomRedeemCode();
        if (redeemCodeList.contains(redeemCode)) {
            createNoRepeatRedeemCode(redeemCodeList);
        } else {
            redeemCodeList.add(redeemCode);
        }
    }

    /**
     * 两个字母 4个数字
     * 生成传入位数的英文字母(大小写)数字随机混排的字符串
     *
     * @return
     */
    private String createRandomRedeemCode() {
        // 确定两个英文的位置（0-5 索引 不重复）
        int firstChar = new Random().nextInt(5);
        int secondChar = getNoRepeatPosition(firstChar);
        String str = "";
        for (int i = 0; i < MagicConstant.INT_SIX; i++) {
            if (i == firstChar || i == secondChar) {
                int intVal = (int) (Math.random() * 26 + 97);
                // 随机大小写
                str += (char) (intVal - ((int) (Math.random() + 0.5) == 1 ? 32 : 0));
            } else {
                str += new Random().nextInt(10);
            }
        }
        return str;
    }

    private int getNoRepeatPosition(int position) {
        int secondChar = new Random().nextInt(5);
        if (secondChar == position) {
            return getNoRepeatPosition(secondChar);
        }
        return secondChar;
    }
}
